import nProgress from 'nprogress'
import 'nprogress/nprogress.css'

import router from '@/router'
import store from '@/store'
// 导入获得标题
import getPageTitle from '@/utils/get-page-title'

const whiteList = ['/login', '/404']
router.beforeEach(async(to, form, next) => {
  nProgress.start()
  const token = store.state.user.token
  // 跳转页面更新标题
  document.title = getPageTitle(to.meta.title)
  if (token) {
    if (to.path === '/login') {
      next('/')
      nProgress.done()
    } else {
      if (!store.state.user.userInfo.userId) {
        await store.dispatch('user/getUserInfo')
      }
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      nProgress.done()
    }
  }
})

router.afterEach(() => {
  nProgress.done()
})
